<!--配送商端-销售管理-寄售补货需求订单列表-发货-->
<template>
  <div class="operation-return">
    <el-container class="container-box">
      <el-header height="auto">
        <div
          class="top-info-box"
          v-loading="topLoading">
          <div
            class="top-info-item"
            v-for="(item,index) in deliverTopInfo"
            :key="index">
            <span class="text-left">{{ item.value }}</span>
            <span
              v-if="item.key==='orderStatus'"
              class="text-right"
            >{{ orderStatus[deliverTopData.orderStatus] }}</span>
            <span
              v-else-if="item.key==='orderTotalAmount'"
              class="text-right"
            >{{ deliverTopData.orderTotalAmount | getFormatterPrice }}</span>
            <el-tooltip
              v-else
              class="item"
              effect="dark"
              :content="deliverTopData[item.key] + '' "
              placement="top-start"
            >
              <span class="text-right">{{ deliverTopData[item.key] }}</span>
            </el-tooltip>
          </div>
        </div>
      </el-header>
      <div class="btn-box">
        <!-- 未实现此功能，所以先隐藏 -->
        <!-- <el-button
          type="primary"
          class="import-btn"
          @click="handleImportDeliverGoodsDetail">
          导入发货详情
        </el-button>
        <el-button
          type="text"
          class="add-btn"
          @click="handleDownloadTemplate">
          下载发货导入模板.cvs
        </el-button>-->
      </div>
      <el-editable
        class="table-box"
        :data="tableData"
        height="200"
        v-loading="tableLoading"
        :columns="deliverGoodsColumns"
        ref="deliveryTable"
      >
        <!-- 发货明细、 -->
        <template
          slot="default-placeholder"
          slot-scope="scope">
          <el-editable
            class="inside-table-box"
            :data="scope.row.distributorList"
            height="200"
            v-loading="insideTableLoading"
            :columns="deliverGoodsColumnsInside"
          />
        </template>
        <!-- 已扫码/待发货数量 -->
        <template
          slot="default-sweepCount"
          slot-scope="scope">
          <span>{{ sweepCodeNum(scope.row) }}</span>
        </template>
        <!-- 操作 -->
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            type="text"
            @click="toGoods(scope)">
            <i class="el-icon-box" />
            去发货
          </el-button>
        </template>
      </el-editable>
      <!-- 去发货弹窗 -->
      <deliver-dialog
        :show.sync="dialogSetting.visible"
        :current-selected-data="currentSelectedData"
        @submitDialog="submitDialog"
      />
      <!-- 分页模块 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
    </el-container>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import ElEditable from '@components/el-editable/index.vue'
import DeliverDialog from '@/moduleComponents/beforeSettle/distributorSide/salesManagement/deliverDialog'

import {
  DELIVER_TOP_INFO,
  DELIVER_GOODS_COLUMNS,
  PART_DETAIL_COLUMNS_INSIDE,
  ORDER_STATUS_TEXT
} from './const.js'
import { isObject, cloneDeep, hasIn } from 'lodash'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
import { getFormatterPrice } from '@const/filter'
// import {  } from '@const/storageCenterApi'
import {
  deliverAddress,
  replenishmentDeliveryTopInfo,
  replenishmentDeliveryList,
  confirmDelivery,
  confirmCodeData
} from '@const/beforeSettleApi'

export default {
  name: 'OperationReturn',
  components: { ElEditable, DeliverDialog },

  data () {
    return {
      orderStatus: ORDER_STATUS_TEXT,
      deliverTopInfo: DELIVER_TOP_INFO,
      deliverTopData: {},
      topLoading: false,
      // 列表配置信息
      tableLoading: false,
      tableData: [{}],
      deliverGoodsColumns: DELIVER_GOODS_COLUMNS,
      insideTableLoading: false,
      deliverGoodsColumnsInside: PART_DETAIL_COLUMNS_INSIDE,
      // 分页配置信息
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      // 发货弹窗信息
      dialogSetting: {
        visible: false
      },
      currentSelectedData: [],

      index: null,
      cloneData: []
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    },
    needPurhcaseId () {
      return this.$route.query.needPurhcaseId
    },
    isCanDeliverGoods () {
      return this.currentSelectedData.length < 1
    }
  },
  filters: {
    getFormatterPrice
  },
  mounted () {
    this.initNavButtons()
    this.getDeliverTopData()
    this.getDeliverTableList()
  },
  methods: {
    // 已扫码数量
    sweepCodeNum (e) {
      let codeNum = 0
      let arr = e.distributorList || []
      arr.forEach(item => {
        codeNum += item.num
      })
      let data = codeNum + '/' + e.awaitSendNum + (e.unit || '')
      e.codeNum = codeNum
      return data
    },
    // 去发货
    toGoods (e) {
      this.dialogSetting.visible = true
      this.index = e.$index
      let arr = []
      arr.push(e.row)
      this.currentSelectedData = arr
      // 深拷贝一份数据给弹框
      // this.cloneData = cloneDeep(this.currentSelectedData)
    },
    ...mapMutations(['changeLayoutHandle']),
    // 初始化 导航栏 按钮组
    initNavButtons () {
      const btn = {
        type: 'btn',
        arr: [
          {
            type: 'button',
            noReturn: true,
            val: '返回',
            handle: this.back
          },
          {
            type: 'primary',
            val: '确认发货',
            handle: this.handleNavBtnSubmit
          }
        ]
      }
      this.changeLayoutHandle(btn)
    },
    // 右上角确认发货按钮
    handleNavBtnSubmit () {
      // 发胡明细
      let arr = []
      this.tableData.forEach(item => {
        if (Number(item.codeNum) !== 0) {
          let obj = {
            orderItemId: item.id,
            sweepCount: item.codeNum,
            distributorList: item.distributorList
          }
          arr.push(obj)
        }
      })
      // 参数
      let data = {
        type: '2',
        orderId: this.deliverTopData.id,
        purchaseOrderId: this.deliverTopData.needPurhcaseId,
        productList: arr
      }
      this.$confirm('确认要发货吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post(confirmDelivery, data).then(res => {
          if (Number(res.data.code) === 0) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            this.back()
          }
        })
      })
    },
    handleImportDeliverGoodsDetail () {
      // 导入发货详情
    },
    handleDownloadTemplate () {
      // 下载模板
    },
    // 提交弹窗中添加的物品详情信息
    submitDialog (sweepCount, itemList) {
      const dateInfo = itemList.map((it, index) => {
        if (it.expDate < it.productDate) return index + 1
      })
      let hasIndex = dateInfo.filter(it => {
        return !(!it || it === '')
      })
      const awaitsendCount = this.currentSelectedData[0].awaitSendNum || 0
      if (itemList.length < 1) {
        this.$message.warning('请扫描或者手动添加物品详情')
        return false
      } else if (sweepCount > awaitsendCount) {
        this.$message.warning('扫码数量不能超过待发货数量')
        return false
      } else if (hasIndex.length > 0) {
        this.$message.warning(`第${hasIndex.join(',')}行有效期不能小于生产日期`)
        return false
      } else {
        this.tableData[this.index].distributorList = itemList
        this.dialogSetting.visible = false
      }
    },
    getDeliverTopData () {
      this.topLoading = true
      this.$axios
        .get(`${replenishmentDeliveryTopInfo}?id=${this.id}`)
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          const baseInfo = data.payload || {}
          let addressId = data.payload.receiveAddressId
          this.getAddressData(baseInfo, addressId)
        })
        .catch(e => {})
        .finally(() => {
          this.topLoading = false
        })
    },
    getAddressData (baseInfo, id) {
      this.topLoading = true
      this.$axios
        .post(`${deliverAddress}?id=${id}`)
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          const {
            province,
            city,
            area,
            detailedAddress,
            userName,
            userPhone
          } = data.payload
          const addressInfo = {
            receiveAddress: `${province} ${city} ${area} ${detailedAddress}`,
            linkMan: userName,
            linkPhone: userPhone
          }
          this.deliverTopData = Object.assign({}, baseInfo, addressInfo)
        })
        .catch(e => {})
        .finally(() => {
          this.topLoading = false
        })
    },
    getDeliverTableList () {
      this.tableLoading = true
      this.$axios
        .post(replenishmentDeliveryList, {
          page: this.curPage,
          pageSize: this.pageSize,
          id: this.id
        })
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          this.tableData = hasIn(data, ['payload']) ? data.payload.content : []
          this.totalElements = data.payload.totalElements
        })
        .catch(e => {})
        .finally(() => {
          this.tableLoading = false
        })
    },
    back () {
      this.$router.go(-1)
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.getDeliverTableList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getDeliverTableList()
    }
  }
}
</script>

<style lang="less">
@import '../m-front-common/pc/assets/var.less';
@textColor: #26344c;
@grayColor: #a7b1c7;
@btnColor: #2371c5;
@white: #fff;

.operation-return {
  .top-info-box {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    .top-info-item {
      width: 33.33%;
      font-size: @defaultFontSize;
      color: @textColor;
      font-weight: 400;
      padding-bottom: 20px;

      .text-left {
        color: @grayColor;
        padding-right: 10px;
        width: 120px;
        text-align: right;
        display: inline-block;
        vertical-align: middle;
      }

      .text-right {
        display: inline-block;
        width: 200px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        vertical-align: middle;
      }
    }
  }

  .container-box {
    height: 100%;
    overflow: auto;

    .btn-box {
      margin-bottom: 16px;

      .import-btn {
        color: @btnColor;
        background-color: @white;
      }
    }

    .inside-table-box {
      width: 1000px;
    }

    .dialog-detail-title {
      padding: 0 0 16px 16px;
    }

    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
